//
//  ZoomImageView.m
//  ZKXSWeibo
//
//  Created by apple on 15/9/18.
//  Copyright (c) 2015年 zhukai. All rights reserved.
//

#import "ZoomImageView.h"

@implementation ZoomImageView
{
    NSURLConnection *_connection;
    double _length; // 图片长度（字节）
    NSMutableData *_data; // 图片数据
    
    MBProgressHUD *_hud;
}

#pragma mark - 初始化方法
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
       
        [self _initTap];
    }
    
    return self;
}
- (void)awakeFromNib {
    [self _initTap];
}
- (instancetype)initWithImage:(UIImage *)image {
    if (self = [super initWithImage:image]) {
        [self _initTap];
    }
    return self;
}
- (void)_initTap {
    
    // 1.打开交互
    self.userInteractionEnabled = YES;
    self.contentMode = UIViewContentModeScaleAspectFit;
    
    // 2.创建单击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomIn)];
    [self addGestureRecognizer:tap];
    
}

// 放大
-(void)zoomIn {
    
    // 调用代理的方法，通知代理
    if ([self.delegate respondsToSelector:@selector(imageWillZoomIn:)]) {
        [self.delegate imageWillZoomIn:self];
    }
    
    // 1.创建大图浏览的_scrollView
    [self _createView];
    
    // 2.计算_fullImageView的frame
    // 把自己相对于父视图的frame转换成相对于window的frame
    CGRect frame = [self convertRect:self.bounds toView:self.window];
    _fullImageView.frame = frame;
    
    // 3.添加动画方法
    [UIView animateWithDuration:0.6 animations:^{
        
        _fullImageView.frame = _scrollView.frame;
    
    } completion:^(BOOL finished) {
        self.hidden = YES;
        _fullImageView.backgroundColor = [UIColor blackColor];
        [self downLoadImage];
    }];
    

    
}
- (void)downLoadImage {
    // 4.请求网络下载原图
    if (_fullImageUrlString.length > 0) {
        
        if (_hud == nil) {
            _hud = [MBProgressHUD showHUDAddedTo:_scrollView animated:YES];
            _hud.mode = MBProgressHUDModeAnnularDeterminate;
            _hud.animationType = MBProgressHUDAnimationFade;
        }
        
        // 存在原图
        NSURL *url = [NSURL URLWithString:_fullImageUrlString];
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
        _connection = [NSURLConnection connectionWithRequest:request delegate:self];
        
    }
}
- (void)zoomOut {
    
    // 调用代理的方法，通知代理
    if ([self.delegate respondsToSelector:@selector(imageWillZoomOut:)]) {
        [self.delegate imageWillZoomOut:self];
    }
    
    // 缩小时先取消网络下载
    [_connection cancel];
    
    _fullImageView.backgroundColor = [UIColor clearColor];
    [UIView animateWithDuration:0.6 animations:^{
        
        CGRect frame = [self convertRect:self.bounds toView:self.window];
        _fullImageView.frame = frame;
        // 计算偏移
        _fullImageView.top += _scrollView.contentOffset.y;
        
    } completion:^(BOOL finished) {
        
        self.hidden = NO;

        [_scrollView removeFromSuperview];
        _scrollView = nil;
        _fullImageView = nil;
        _hud = nil;
        
    }];
    
}
- (void)_createView {
    
    if (_scrollView == nil) {
        // 1.创建_scrollView，添加到window 上
        _scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        // 隐藏滑动条
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;

        
        [self.window addSubview:_scrollView];
        
        // 2.创建大图 _fullImageView
        _fullImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        // 设置大图等比例缩放
        _fullImageView.contentMode = UIViewContentModeScaleAspectFit;
        _fullImageView.image = self.image;
        
        [_scrollView addSubview:_fullImageView];
        
        // 3.添加缩小手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zoomOut)];
        [_scrollView addGestureRecognizer:tap];
        
        // 4.长按保存
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(savePhoto:)];
        [_scrollView addGestureRecognizer:longPress];
    }
    
}


#pragma mark - 保存事件
- (void)savePhoto:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否保存图片" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        [alert show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 点击“是”按钮
    if (buttonIndex == 1) {
        UIImage *image = _fullImageView.image;
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
    
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"qqicon"]];
    // 显示模式改为：自定义模式
    hud.mode = MBProgressHUDModeCustomView;
    hud.labelText = @"保存成功";
    
    [hud hide:YES afterDelay:1.5];
}

#pragma mark - 网络下载监控
// 服务器响应请求（之调用一次）
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    // 1.取得响应头
    NSDictionary *headerFields = httpResponse.allHeaderFields;
    
    // 2.获取文件大小
    NSString *lengthStr = [headerFields objectForKey:@"Content-length"];
    _length = [lengthStr doubleValue];
    
    _data = [[NSMutableData alloc] init];
    
}
// 接收到一次数据（多次调用，文件大的话会调用多次）
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    [_data appendData:data];
    // 进度百分比
    CGFloat progress = _data.length / _length;
    _hud.progress = progress;
}
// 下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    NSLog(@"下载完毕");
    UIImage *image = [UIImage imageWithData:_data];
    _fullImageView.image = image;
    
    // 隐藏hud
    _hud.hidden = YES;
    
    // 尺寸处理
    CGFloat height = image.size.height / image.size.width * SCREEN_WIDTH;
    if (height > SCREEN_HEIGHT) {
        [UIView animateWithDuration:0.3 animations:^{
            _fullImageView.height = height;
            _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, height);
        }];
        
    }
}
@end